package cn.buddha.jesa.conditional.bean.config;

import cn.buddha.jesa.conditional.bean.model.City;
import cn.buddha.jesa.conditional.bean.model.Human;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName ConditionalBeanConfig
 * @Author 友野浩二
 * @Date 2020/1/8 14:20
 * @Description 配置
 * @Version 1.0
 */
@Configuration
@Slf4j
public class ConditionalBeanConfig {

//    @Bean(name = "city")
//    public City city1() {
//        return City.builder().cityCode("001").cityName("掠食城市").build();
//    }

    // 这里，我们要干这样一件事。当city没有注入的时候，则注入备用的city
    @ConditionalOnMissingBean({City.class})// 当给定的bean不存在时,则实例化当前Bean
    @Bean(name = "spareCity")
    public City city2() {
        return City.builder().cityCode("002").cityName("汉城").build();
    }

    @ConditionalOnBean({City.class})// 当给定的bean存在时,则实例化当前Bean
    @Bean
    public Human human(City city) {
        // 注意：如果city没有注入，则此处会报空指针异常
        return Human.builder().name("tong").sex("女").age(26).city(city).build();
    }

}
